<?php

/**
 * Description of MySQL
 *
 * @author Le Trung Dung
 */
class MySQL {

    /**
     * Kiểu return dữ liệu mysql
     * FETCH_OBJ, FETCH_ASSOC, FETCH_ARRAY
     * @var type 
     */
    private $_fetchMode = "FETCH_OBJ";
    /**
     * Connection 
     * @var type 
     */
    private $connection = NULL;
    private $result = NULL;
    /**
     * Thông tin database
     * @var type 
     */
    private $_host = NULL;
    private $_dbname = NULL;
    private $_username = NULL;
    private $_password = NULL;
    protected static $_instance = null;

    private function __clone() {
        
    }

    public static function getInstance() {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function setConection($config) {
        $this->_host = $config['host'];
        $this->_dbname = $config['dbname'];
        $this->_username = $config['username'];
        $this->_password = $config['password'];
    }

    /**
     * Set fetch Mode
     * @param type $mode 
     */
    public function setFetchMode($mode) {
        $this->_fetchMode = $mode;
    }

    /**
     * Kết nối tới database
     */
    public function connect() {
        try {
            $this->connection = @mysql_connect(
                    $this->_host, $this->_username, $this->_password, TRUE
            );
            @mysql_select_db($this->_dbname, $this->connection);
            $this->query("SET NAMES 'utf8'");
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    }

    /**
     * Đóng kết nối
     */
    public function disconnect() {
        try {
            if (is_resource($this->connection)) {
                mysql_close($this->connection);
            }
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    }

    /**
     * Query SQL
     * @param text $query 
     */
    public function query($query) {
        try {
            if (is_resource($this->connection)) {
                if (is_resource($this->result)) {
                    @mysql_free_result($this->result);
                }
                $this->result = mysql_query($query, $this->connection);
                return $this->result;
            }
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    }

    public function fetchRow($query = null) {
        try {
            if ($query) {
                $this->result = $this->query($query);
            }

            if (is_resource($this->result)) {
                // Check Fetch Mode
                // FETCH_OBJ
                if ($this->_fetchMode == "FETCH_OBJ") {
                    $row = mysql_fetch_object($this->result);
                    if (is_object($row)) {
                        return $row;
                    }


                    // FETCH_ASSOC
                } else if ($this->_fetchMode == "FETCH_ASSOC") {
                    $row = mysql_fetch_assoc($this->result);
                    if (is_array($row)) {
                        return $row;
                    }


                    // FETCH_ARRAY
                } else {
                    $row = mysql_fetch_array($this->result);
                    if (is_array($row)) {
                        return $row;
                    }
                }
                return FALSE;
            }
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    }

    function fetchAll($query = null) {
        try {
            if ($query) {
                $this->result = $this->query($query);
            }
            
            if (is_resource($this->result)) {
                $obj = NULL;
                while ($rs = $this->fetchRow())
                    $obj[] = $rs;
                @mysql_free_result($this->result);
                return $obj;
            }
            return false;
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    }

    /**
     *
     * @param text $table
     * @param array $data
     * @return integer 
     */
    function insert($table, $data) {
        try {
            if (is_array($data)) {
                //TODO Nối các field lại với nhau dưới dạng array
                foreach ($data as $key => $value) {
                    $insert_field[] = $key;
                    $insert_value[] = $value;
                }

                //TODO Nối các field lại với nhau dưới dạng text sql
                $insert_field = implode(", ", $insert_field);
                $insert_value = implode("', '", $insert_value);

                //TODO INSERT SQL
                $insert = $this->query("INSERT INTO $table ($insert_field) VALUES ('$insert_value')");
                if ($insert) {
                    //TODO Trả về id vừa insert
                    return $this->lastInsertId();
                }
                return false;
            } else {
                return false;
            }
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    }

    /**
     *
     * @param text $table
     * @param array $data
     * @param text $where
     * @return boolean 
     */
    function update($table, $data, $where) {
        try {
            if (is_array($data)) {
                //TODO Nối các field lại với nhau dưới dạng array
                foreach ($data as $key => $value)
                    $update_field[] = "$key = '$value'";

                //TODO Nối các field lại với nhau dưới dạng text sql
                $update_field = implode(", ", $update_field);

                //TODO Update SQL
                $update = $this->query("UPDATE $table SET $update_field WHERE $where");
                if ($update) {
                    return true;
                }
                return false;
            } else {
                return false;
            }
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    }

    /**
     *
     * @param text $table
     * @param text $where
     * @return boolean 
     */
    function delete($table, $where) {
        try {
            $delete = $this->query("DELETE FROM $table WHERE $where");
            if ($delete)
                return true; else
                return false;
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    }

    /**
     * Trả về tổng số row
     * @return type 
     */
    function rowCount() {
        try {
            return @mysql_affected_rows();
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    }

    /**
     * Trả về id cuối cùng vừa insert
     * @return type 
     */
    function lastInsertId() {
        try {
            return @mysql_insert_id();
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    }

    /**
     * Get Error Code(Error Number)
     * return: ErrorNo neu khong thuc hien duoc cau truy van
     * NULL: neu viec thuc hien thanh cong
     * @return type 
     */
    function errorCode() {
        try {
            return mysql_errno();
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    }

    /**
     * Get Error Info
     * return: Array info about mysql
     * NULL: if not error
     * @return type 
     */
    function errorInfo() {
        try {
            if ($this->errorCode()) {
                $obj[0] = $this->errorCode();
                $obj[2] = mysql_error();
                return $obj;
            }
            return false;
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    }

}

?>
